<template>
  <div class="record-container">
    <!-- 紧凑型日期选择器 -->
    <div class="date-picker-container">
      <div class="date-picker-wrapper">
        <el-date-picker v-model="dateRange.start" type="date" placeholder="起始日期" class="date-input" value-format="YYYY-MM-DD" :clearable="false" />
      </div>
      <span class="date-separator">至</span>
      <div class="date-picker-wrapper">
        <el-date-picker v-model="dateRange.end" type="date" placeholder="结束日期" class="date-input" value-format="YYYY-MM-DD" :clearable="false" :popper-options="{
                      placement: 'bottom-end',
                      boundariesPadding: 5,
                      preventOverflow: true
                    }" />
      </div>
    </div>

    <!-- 部门选择 -->
    <el-select v-model="selectedDeptId" placeholder="选择部门" clearable filterable @change="handleDeptChange" class="dept-select">
      <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
    </el-select>

    <!-- 员工选择 -->
    <el-select v-model="selectedEmpId" placeholder="选择员工" clearable filterable :disabled="!selectedDeptId" class="emp-select">
      <el-option v-for="emp in employeeList" :key="emp.empId" :label="`${emp.empId} ${emp.name}`" :value="emp.empId" />
    </el-select>

    <!-- 查询按钮 -->
    <div class="query-button-container">
      <el-button type="primary" class="query-button" @click="handleQuery" :loading="isQuerying">
        查询
      </el-button>
    </div>

    <!-- 考勤记录列表 -->
    <div class="record-list">
      <!-- 显示查询结果 -->
      <template v-if="showResult">
        <!-- 查询单个员工时的显示方式 -->
        <template v-if="!lastQueryIsMultiEmployee">
          <div class="record-item" v-for="(record, index) in attendanceRecords" :key="index">
            <div class="record-left">
              <div class="record-date">{{ formatDate(record.date) }}</div>
              <div class="record-time">
                <span class="time-label">签到：</span>
                <span v-if="record.checkInTime">{{ formatTime(record.checkInTime) }}</span>
                <span v-else class="absent">未签到</span>
              </div>
              <div class="record-time" v-if="record.checkOutTime || showAllRecords">
                <span class="time-label">签退：</span>
                <span v-if="record.checkOutTime">{{ formatTime(record.checkOutTime) }}</span>
                <span v-else class="absent">未签退</span>
              </div>
            </div>
            <div class="record-status">
              <el-tag :type="getStatusTagType(record.status)" size="small" effect="plain">
                {{ getStatusText(record.status) }}
              </el-tag>
            </div>
          </div>
        </template>

        <!-- 查询多个员工时的显示方式 -->
        <template v-else>
          <div class="date-group" v-for="(group, date) in groupedRecords" :key="date">
            <div class="group-date">{{ formatDate(date) }}</div>
            <div class="employee-records">
              <div class="employee-record" v-for="(record, index) in group" :key="index">
                <div class="record-left">
                  <div class="record-name">{{ getEmployeeName(record.empId) }}</div>
                  <div class="record-time">
                    <span class="time-label">签到：</span>
                    <span v-if="record.checkInTime">{{ formatTime(record.checkInTime) }}</span>
                    <span v-else class="absent">未签到</span>
                  </div>
                  <div class="record-time" v-if="record.checkOutTime || showAllRecords">
                    <span class="time-label">签退：</span>
                    <span v-if="record.checkOutTime">{{ formatTime(record.checkOutTime) }}</span>
                    <span v-else class="absent">未签退</span>
                  </div>
                </div>
                <div class="record-status">
                  <el-tag :type="getStatusTagType(record.status)" size="small" effect="plain">
                    {{ getStatusText(record.status) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </template>
      </template>

      <div class="no-more-data">
        <el-divider />
        <div class="no-more-text">没有更多数据了</div>
      </div>
    </div>
  </div>
</template>
    
    <script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getSubDeptIds, getEmployeesUnderDept } from "../../api/dept.js";
import { getDeptAttendance } from "../../api/attendance.js";
import dayjs from "dayjs";

// 日期范围选择
const dateRange = ref({ start: null, end: null });

// 部门相关数据
const deptList = ref([]);
const selectedDeptId = ref(null);

// 员工相关数据
const employeeList = ref([]);
const selectedEmpId = ref(null);

// 考勤记录数据
const attendanceRecords = ref([]);
const isQuerying = ref(false);
const showAllRecords = ref(true);
const showResult = ref(false); // 是否显示查询结果
const lastQueryIsMultiEmployee = ref(false); // 上次查询是否为多员工模式

// 状态映射
const statusMap = {
  0: { text: "未知", type: "info" },
  1: { text: "请假", type: "" },
  2: { text: "出差", type: "" },
  3: { text: "正常签到", type: "success" },
  4: { text: "迟到", type: "warning" },
  5: { text: "旷工", type: "danger" },
  6: { text: "早退", type: "warning" },
  7: { text: "部分出勤", type: "warning" },
  8: { text: "正常出勤", type: "success" },
};

// 计算属性：按日期分组的记录
const groupedRecords = computed(() => {
  const groups = {};
  attendanceRecords.value.forEach((record) => {
    if (!groups[record.date]) {
      groups[record.date] = [];
    }
    groups[record.date].push(record);
  });
  return groups;
});

// 加载部门列表
const loadDeptList = () => {
  getSubDeptIds()
    .then((res) => {
      if (res.flag) {
        deptList.value = (res.result || []).map((dept) => ({
          id: dept.id || 0,
          name: dept.name || "未知部门",
        }));
      } else {
        ElMessage.warning(res.reason || "获取部门列表失败");
      }
    })
    .catch((err) => {
      console.error("获取部门列表失败:", err);
      ElMessage.error(err.response?.data?.reason || "网络错误");
    });
};

// 部门变更处理
const handleDeptChange = (deptId) => {
  selectedEmpId.value = null;
  employeeList.value = [];

  if (deptId) {
    const selectedDept = deptList.value.find((d) => d.id === deptId);
    if (!selectedDept) return;

    getEmployeesUnderDept({ deptName: selectedDept.name })
      .then((res) => {
        if (res.flag) {
          employeeList.value = (res.result || []).map((emp) => ({
            empId: emp.empId || "",
            name: emp.name || "未知员工",
          }));
        } else {
          ElMessage.warning(res.reason || "获取员工列表失败");
        }
      })
      .catch((err) => {
        console.error("获取员工列表失败:", err);
        ElMessage.error(err.response?.data?.reason || "网络错误");
      });
  }
};

// 格式化日期时间
const formatDate = (dateStr) => dayjs(dateStr).format("YYYY.MM.DD");
const formatTime = (datetimeStr) =>
  dayjs(datetimeStr).format("YY/MM/DD HH:mm:ss");

// 获取状态显示
const getStatusText = (status) => statusMap[status]?.text || "未知状态";
const getStatusTagType = (status) => statusMap[status]?.type || "";

// 根据员工ID获取员工姓名
const getEmployeeName = (empId) => {
  const emp = employeeList.value.find((e) => e.empId === empId);
  return emp ? `${emp.empId} ${emp.name}` : "未知员工";
};

// 查询考勤记录
const handleQuery = async () => {
  if (!dateRange.value.start || !dateRange.value.end) {
    ElMessage.warning("请选择起始日期和结束日期");
    return;
  }

  if (!selectedDeptId.value) {
    ElMessage.warning("请选择部门");
    return;
  }

  isQuerying.value = true;
  showResult.value = true;

  const params = {
    startDate: dayjs(dateRange.value.start).format("YYYY-MM-DD"),
    endDate: dayjs(dateRange.value.end).format("YYYY-MM-DD"),
    deptId: selectedDeptId.value,
    underEmpId: selectedEmpId.value || null,
  };

  // 记录当前是否为多员工查询
  lastQueryIsMultiEmployee.value = !selectedEmpId.value;

  // 记录当前员工列表快照
  const currentEmployeeList = [...employeeList.value];

  await getDeptAttendance(params)
    .then((res) => {
      if (res.flag) {
        // 将员工信息附加到考勤记录中
        attendanceRecords.value = (res.result || []).map((record) => {
          const emp = currentEmployeeList.find((e) => e.empId === record.empId);
          return {
            ...record,
            empName: emp ? `${emp.empId} ${emp.name}` : "未知员工",
          };
        });
      } else {
        ElMessage.warning(res.reason || "查询失败");
        attendanceRecords.value = [];
      }
    })
    .catch((err) => {
      console.error("请求失败:", err.message);
      ElMessage.error(err.message);
      console.error("查询失败:", err);
      ElMessage.error(err.response?.data?.reason || "网络错误");
      attendanceRecords.value = [];
    })
    .finally(() => {
      isQuerying.value = false;
    });
};

// 页面加载时只加载部门列表
onMounted(() => {
  loadDeptList();
});
</script>
    
    <style scoped>
:deep(.el-date-editor) {
  width: 40.5vw;
}
.record-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 8px;
  max-width: 100%;
  overflow-x: hidden;
  min-height: 80vh;
}

.date-picker-container {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: nowrap;
  width: 100%;
  max-width: 100%;
  position: relative;
  margin-top: 2vh;
}

.date-picker-wrapper {
  flex: 1;
  min-width: 0;
  position: relative;
}

.date-input {
  width: 100%;
  padding: 8px 4px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
}

.date-input::placeholder {
  text-align: center;
}

.date-separator {
  color: #666;
  font-size: 12px;
  padding: 0 2px;
  white-space: nowrap;
  flex-shrink: 0;
}

.query-button-container {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-bottom: 8px;
}

.query-button {
  padding: 8px 20px;
  font-size: 14px;
  width: 100%;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}

.empty-tip {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* 单个员工记录样式 */
.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background-color: white;
  border-radius: 4px;
}

/* 多个员工记录样式 */
.date-group {
  background-color: white;
  border-radius: 4px;
  margin-bottom: 8px;
}

.group-date {
  padding: 10px 12px;
  font-weight: bold;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}

.employee-records {
  display: flex;
  flex-direction: column;
}

.employee-record {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  border-bottom: 1px solid #f5f5f5;
}

.employee-record:last-child {
  border-bottom: none;
}

.record-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.record-date,
.record-name {
  font-weight: 500;
  font-size: 14px;
  color: #1a1a1a;
}

.record-time {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
}

.time-label {
  color: #999;
  margin-right: 4px;
  min-width: 36px;
}

.record-status {
  margin-left: 12px;
  flex-shrink: 0;
}

.absent {
  color: #f56c6c;
}

.no-more-data {
  text-align: center;
  margin-top: 10px;
  padding: 0 12px;
}

.no-more-data :deep(.el-divider) {
  background-color: #e0e0e0; /* 加深分割线颜色 */
}

.no-more-text {
  color: #999;
  font-size: 12px;
  margin-top: -10px;
  background: white;
  display: inline-block;
  padding: 0 10px;
}
</style>